package com.ys.erp.framework.handler.check;

import com.ys.erp.framework.annotation.CheckAdminPermissions;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * 校验当前用户角色权限
 *
 * @author scy
 * @date 2021/5/9
 */
@Slf4j
public abstract class CheckAdminPermissionsHandler {

    /**
     * 切入点
     */
    @Pointcut(value = "@within(com.ys.erp.framework.annotation.CheckAdminPermissions) ")
    public void permissionTypeCheckCut() {
    }

    @Pointcut(value = "@annotation(com.ys.erp.framework.annotation.CheckAdminPermissions)")
    public void permissionMethodCheckCut() {

    }

    /**
     * 检查admin
     *
     * @param request request
     * @param permission targetMethod
     */
    public abstract void checkAdminPermission(HttpServletRequest request, CheckAdminPermissions permission);

    @Before("permissionTypeCheckCut()")
    public void doBefore(JoinPoint pj) throws Throwable {
        Class<?> aClass = pj.getTarget().getClass();
        CheckAdminPermissions annotation = aClass.getAnnotation(CheckAdminPermissions.class);
        //根据请求头的token获取当前登录用户
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        checkAdminPermission(request, annotation);
    }

    @Before("permissionMethodCheckCut()")
    public void around(JoinPoint pj) throws Throwable {
        Signature signature = pj.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        CheckAdminPermissions annotation = targetMethod.getAnnotation(CheckAdminPermissions.class);
        //根据请求头的token获取当前登录用户
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        checkAdminPermission(request, annotation);
    }

}
